//
//  AppDelegate.m
//  MRBang
//
//  Created by 铅笔 on 15/12/14.
//  Copyright © 2015年 杭州易网新科技. All rights reserved.
//

#import "AppDelegate.h"
#import "myTabBarViewController.h"

#import "LoginViewController.h"//暂时

#import <Bugly/CrashReporter.h>//崩溃

// 信鸽推送
#import "XGPush.h"
#import "XGSetting.h"

#define _IPHONE80_ 80000


@interface AppDelegate ()
{

    UIView *view_second;//第二个 重置密码背景
    UIView *view_middleBG;//解决 home后 进入app出现原有页面的问题
}

@property (nonatomic,strong) UIView *view_lockBG;

@end

@implementation AppDelegate
- (void)registerPushForIOS8{
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= _IPHONE80_
    
    //Types
    UIUserNotificationType types = UIUserNotificationTypeBadge | UIUserNotificationTypeSound | UIUserNotificationTypeAlert;
    
    //Actions
    UIMutableUserNotificationAction *acceptAction = [[UIMutableUserNotificationAction alloc] init];
    
    acceptAction.identifier = @"ACCEPT_IDENTIFIER";
    acceptAction.title = @"Accept";
    
    acceptAction.activationMode = UIUserNotificationActivationModeForeground;
    acceptAction.destructive = NO;
    acceptAction.authenticationRequired = NO;
    
    //Categories
    UIMutableUserNotificationCategory *inviteCategory = [[UIMutableUserNotificationCategory alloc] init];
    
    inviteCategory.identifier = @"INVITE_CATEGORY";
    
    [inviteCategory setActions:@[acceptAction] forContext:UIUserNotificationActionContextDefault];
    
    [inviteCategory setActions:@[acceptAction] forContext:UIUserNotificationActionContextMinimal];
    
    NSSet *categories = [NSSet setWithObjects:inviteCategory, nil];
    
    
    UIUserNotificationSettings *mySettings = [UIUserNotificationSettings settingsForTypes:types categories:categories];
    
    [[UIApplication sharedApplication] registerUserNotificationSettings:mySettings];
    
    
    [[UIApplication sharedApplication] registerForRemoteNotifications];
#endif
}

- (void)registerPush{
    [[UIApplication sharedApplication] registerForRemoteNotificationTypes:(UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound)];
}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    
     [self.window setRootViewController:[myTabBarViewController new]];
    
    //测试崩溃
      [[CrashReporter sharedInstance] installWithAppId:@"900022392"];
    
    //信鸽推送
    //初始化app
    [XGPush startApp:2200195954 appKey:@"I1ID7KE533UP"];
    
    //注销之后需要再次注册前的准备
    void (^successCallback)(void) = ^(void){
        //如果变成需要注册状态
        if(![XGPush isUnRegisterStatus])
        {
            //iOS8注册push方法
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= _IPHONE80_
            
            float sysVer = [[[UIDevice currentDevice] systemVersion] floatValue];
            if(sysVer < 8){
                [self registerPush];
            }
            else{
                [self registerPushForIOS8];
            }
#else
            //iOS8之前注册push方法
            //注册Push服务，注册后才能收到推送
            [self registerPush];
#endif
        }
    };
    [XGPush initForReregister:successCallback];
    
    //推送反馈回调版本示例
    void (^successBlock)(void) = ^(void){
        //成功之后的处理
        NSLog(@"[XGPush]handleLaunching's successBlock");
    };
    
    void (^errorBlock)(void) = ^(void){
        //失败之后的处理
        NSLog(@"[XGPush]handleLaunching's errorBlock");
    };
    
    //角标清0
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
    
    [XGPush handleLaunching:launchOptions successCallback:successBlock errorCallback:errorBlock];
    
    //状态栏颜色
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];

    [self.window makeKeyAndVisible];
    return YES;
}

-(void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification{
    //notification是发送推送时传入的字典信息
    [XGPush localNotificationAtFrontEnd:notification userInfoKey:@"clockID" userInfoValue:@"myid"];
    
    //删除推送列表中的这一条
    [XGPush delLocalNotification:notification];
}

#if __IPHONE_OS_VERSION_MAX_ALLOWED >= _IPHONE80_

//注册UserNotification成功的回调
- (void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings
{
    //用户已经允许接收以下类型的推送
    //UIUserNotificationType allowedTypes = [notificationSettings types];
    
}

//按钮点击事件回调
- (void)application:(UIApplication *)application handleActionWithIdentifier:(NSString *)identifier forRemoteNotification:(NSDictionary *)userInfo completionHandler:(void (^)())completionHandler{
    if([identifier isEqualToString:@"ACCEPT_IDENTIFIER"]){
        NSLog(@"ACCEPT_IDENTIFIER is clicked");
    }
    
    completionHandler();
}

#endif

- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    
    void (^successBlock)(void) = ^(void){
        //成功之后的处理
        NSLog(@"[XGPush Demo]register successBlock");
    };
    
    void (^errorBlock)(void) = ^(void){
        //失败之后的处理
        NSLog(@"[XGPush Demo]register errorBlock");
    };
    
    //注册设备
    NSString * deviceTokenStr = [XGPush registerDevice:deviceToken successCallback:successBlock errorCallback:errorBlock];
    
    //打印获取的deviceToken的字符串
    NSLog(@"[XGPush Demo] deviceTokenStr is %@",deviceTokenStr);
}

//如果deviceToken获取不到会进入此事件
- (void)application:(UIApplication *)app didFailToRegisterForRemoteNotificationsWithError:(NSError *)err {
    
    NSString *str = [NSString stringWithFormat: @"Error: %@",err];
    
    NSLog(@"[XGPush Demo]%@",str);
    
}

- (void)application:(UIApplication*)application didReceiveRemoteNotification:(NSDictionary*)userInfo
{
    //推送反馈(app运行时)
    [XGPush handleReceiveNotification:userInfo];
    
    
    //回调版本示例
    /*
     void (^successBlock)(void) = ^(void){
     //成功之后的处理
     NSLog(@"[XGPush]handleReceiveNotification successBlock");
     };
     
     void (^errorBlock)(void) = ^(void){
     //失败之后的处理
     NSLog(@"[XGPush]handleReceiveNotification errorBlock");
     };
     
     void (^completion)(void) = ^(void){
     //完成之后的处理
     NSLog(@"[xg push completion]userInfo is %@",userInfo);
     };
     
     [XGPush handleReceiveNotification:userInfo successCallback:successBlock errorCallback:errorBlock completion:completion];
     */
}

- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
    
    if ([[NSUserDefaults standardUserDefaults] objectForKey:@"isOpenGestureLock"]) {
        view_middleBG = [[UIView alloc] initWithFrame:self.window.frame];
        [self.window addSubview:view_middleBG];
        view_middleBG.backgroundColor = COLOR_EVERYVIEWBG;
    }
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.

}

#pragma mark --- 将要进入 次此app1
- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
    
    if ([[NSUserDefaults standardUserDefaults] objectForKey:@"isOpenGestureLock"]) {
        
        //移除中间间隔时间所添加的页面
        [view_middleBG removeFromSuperview];
        
        self.view_lockBG = [[UIView alloc] initWithFrame:self.window.frame];
        [self.window addSubview:self.view_lockBG];
        self.view_lockBG.backgroundColor = COLOR_EVERYVIEWBG;
        
        //设置 九课按钮
        [self initWithShowUnlockPageVCSubviews];
        
        //忘记手势密码
        UIButton *button_forgetGesture = [[UIButton alloc] initWithFrame:CGRectMake(kScreenWidth-120, kScreenHeight-50, 120, 30)];
        [self.view_lockBG addSubview:button_forgetGesture];
        [button_forgetGesture setTitle:@"忘记手势密码?" forState:UIControlStateNormal];
        [button_forgetGesture setTitleColor:RXDColor(59, 167, 217) forState:UIControlStateNormal];
        [button_forgetGesture.titleLabel setFont:[UIFont systemFontOfSize:Font_SIZE_22]];
        [button_forgetGesture addTarget:self action:@selector(forgetGesturePasswordAction) forControlEvents:UIControlEventTouchUpInside];
    }
}

/**
 * 进入的时候 输入手势密码
 */
- (void) initWithShowUnlockPageVCSubviews
{
    UIImageView *imageView_icon = [[UIImageView alloc] initWithFrame:CGRectMake(self.window.frame.size.width/2-40,80, 80, 80)];
    [self.view_lockBG addSubview:imageView_icon];
    imageView_icon.image = [UIImage imageNamed:@"ic_mrbang"];
    
    UILabel * label_tips = [[UILabel alloc] initWithFrame:CGRectMake(30*PROPORTION_WIDTH, imageView_icon.bottom+30, kScreenWidth-30*PROPORTION_WIDTH*2,30*PROPORTION_WIDTH)];
    [self.view_lockBG addSubview:label_tips];
    label_tips.textAlignment = NSTextAlignmentCenter;
    label_tips.textColor = COLOT_TEXTGRAY;
    label_tips.font = [UIFont systemFontOfSize:Font_SIZE_24];
    
    NSLog(@"DBGuestureLock  %@--%@--",[DBGuestureLock getGuestureLockPassword],DBFirstTimeSetupPassword);

    //Working with block:
    DBGuestureLock *lock = [DBGuestureLock lockOnView:self.window onPasswordSet:^(DBGuestureLock *lock, NSString *password) {
//        if (lock.firstTimeSetupPassword == nil) {
//            lock.firstTimeSetupPassword = password;
//            NSLog(@"varify your password");
//        }
    } onGetCorrectPswd:^(DBGuestureLock *lock, NSString *password) {
        if (lock.firstTimeSetupPassword && ![lock.firstTimeSetupPassword isEqualToString:DBFirstTimeSetupPassword]) {
            lock.firstTimeSetupPassword = DBFirstTimeSetupPassword;
            NSLog(@"password has been setup!");
            
        } else {
            NSLog(@"login success");
            
            [self.view_lockBG removeFromSuperview];
            
        }
    } onGetIncorrectPswd:^(DBGuestureLock *lock, NSString *password) {
        if (![lock.firstTimeSetupPassword isEqualToString:DBFirstTimeSetupPassword]) {
            NSLog(@"Error: password not equal to first setup!");
            
            label_tips.text = @"密码错误，请重新输入或重置／退出应用重新进入";
            
            
        } else {
            NSLog(@"login failed");
        }
    }];
    
    [self.view_lockBG addSubview:lock];
    
    label_tips.text = @"请输入手势密码";
}

#pragma mark --- 忘记手势
- (void) forgetGesturePasswordAction
{
    //退出登录
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"memberid"];
    [[NSUserDefaults standardUserDefaults] synchronize];
    
    [self.view_lockBG removeFromSuperview];
    
    LoginViewController *longin = [[LoginViewController alloc] init];
    
    longin.fromeWhere = @"appdelegate";

    UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:longin];

    self.window.rootViewController = nav;
}

#pragma mark --- 将要进入 次此app2
- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    
    //移除掉 手势解锁标记
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"indexTabbar"];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

#pragma mark - Welcome Page


@end
